# -*- coding: utf-8 -*-
from flask_wtf import FlaskForm as Form
from wtforms import StringField, PasswordField, SubmitField, BooleanField, \
    SelectField
from wtforms.validators import DataRequired, Length, Email, EqualTo
from wtforms.validators import ValidationError

from ..models import User


class EditForm(Form):
    def __init__(self, id, *args, **kwargs):
        super(EditForm, self).__init__(*args, **kwargs)
        self.id = id

    nickname = StringField(u'昵称', validators=[DataRequired(), Length(3, 15)])
    username = StringField(u'邮箱', validators=[DataRequired(), Length(1, 64),
                                              Email()])
    role = SelectField(u'角色', coerce=int, validators=[DataRequired()])
    status = SelectField(u'状态', coerce=int)
    submit = SubmitField(u'修改')

    def validate_username(self, field):
        user = User.query.get_or_404(self.id)
        if user.username != field.data and \
                User.query.filter_by(username=field.data).first():
            raise ValidationError(u'邮箱已经注册。')

    def validate_nickname(self, field):
        user = User.query.get_or_404(self.id)
        if user.nickname != field.data and \
                User.query.filter_by(nickname=field.data).first():
            raise ValidationError(u'昵称已经被使用。')


class ChangePassword(Form):
    new_password = PasswordField(u'新密码', validators=[DataRequired()])
    confirm_password = PasswordField(u'确认密码',
                                     validators=[DataRequired(),
                                                 EqualTo('new_password', message=u'确认密码与密码不相同。')])
    submit = SubmitField(u'修改')
